<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会员名称" prop="memberTypeName">
        <el-input
          v-model="queryParams.memberTypeName"
          placeholder="请输入会员名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卡的天数" prop="cardDays">
        <el-input
          v-model="queryParams.cardDays"
          placeholder="请输入卡的天数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['memberTypeManagement:management:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['memberTypeManagement:management:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="managementList">
      <el-table-column label="会员卡序号" align="center" prop="id"/>
      <el-table-column label="会员类型" align="center" prop="memberType">
        <template slot-scope="scope">
          <span v-if="scope.row.memberType === 0">次卡</span>
          <span v-if="scope.row.memberType === 1">月卡</span>
          <span v-if="scope.row.memberType === 2">年卡</span>
          <span v-if="scope.row.memberType === 3">体验卡</span>
        </template>
      </el-table-column>
      <el-table-column label="卡的天数" align="center" prop="cardDays"/>
      <el-table-column label="会员名称" align="center" prop="memberTypeName"/>
      <el-table-column label="会员备注" align="center" prop="memberTypeRemarks"/>
      <el-table-column
        align="center"
        prop="enableStatus"
        label="启用/禁用"
      >
        <!-- 滑块开关 -->
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.enableStatus === 1"> 禁用</el-tag>
          <el-tag type="success" v-else> 正常</el-tag>
        </template>
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enableStatus"
                     active-color="#13ce66"
                     inactive-color="#ff4949"
                     :active-value="0"
                     :inactive-value="1"
                     @change=toggleDisableStatus(scope.row)
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="会员卡的类别" align="center" prop="categoryId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.type_card" :value="scope.row.categoryId"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['memberTypeManagement:management:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['memberTypeManagement:management:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改会员类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="会员类型" prop="memberType">
          <el-select v-model="form.memberType" placeholder="请选择会员类型" @change="updateCardDays">
            <el-option label="次卡" :value="0"></el-option>
            <el-option label="月卡" :value="1"></el-option>
            <el-option label="年卡" :value="2"></el-option>
            <el-option label="体验卡" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员卡的类别" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择会员卡的类别">
            <el-option
              v-for="dict in dict.type.type_card"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员卡名称" prop="memberTypeName">
          <el-input v-model="form.memberTypeName" placeholder="请输入会员卡名称"/>
        </el-form-item>
        <el-form-item v-if="form.memberType !== null" :label="cardDaysLabel" prop="cardDays">
          <el-input v-model="form.cardDays" :placeholder="cardDaysPlaceholder"  :rules="rules.cardDays"></el-input>
        </el-form-item>
        <el-form-item label="会员备注" prop="memberTypeRemarks">
          <el-input v-model="form.memberTypeRemarks" placeholder="请输入会员备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listManagement,
  getManagement,
  delManagement,
  addManagement,
  updateManagement,
  updateManagementState
} from '@/api/memberTypeManagement/management'
export default {
  name: 'Management',
  dicts: ['type_card'],
  data() {
    return {
      //判断卡天数的格式
      cardDays: '',
      //判断是否需要表单校验
      isCardTypeSelected: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员类型表格数据
      managementList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        venueUniqueIdentifier: null,
        memberType: null,
        cardDays: null,
        memberTypeName: null,
        memberTypeRemarks: null,
        enableStatus: null,
        categoryId:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        memberTypeRemarks:[
          { required: true, message: '请输入会员备注', trigger: 'change' }
        ],
        memberType: [
          { required: true, message: '请选择会员类型', trigger: 'change' }
        ],
        memberTypeName: [
          { required: true, message: '请输入会员卡名称', trigger: 'blur' }
        ],
        cardDays: [],
        categoryId: [
          { required: true, message: "会员卡的类别不能为空", trigger: "change" }
        ]
      }
    }
  },
  computed: {
    cardDaysLabel() {
      return this.form.memberType === 0 ? '会员卡次数' : '会员卡天数';
    },
    cardDaysPlaceholder() {
      return this.form.memberType === 0 ? '请输入会员卡次数' : '请输入会员卡天数';
    }
  },
  watch: {
    // 监听 form.memberType 的变化
    'form.memberType': function(newVal) {
      // 根据 newVal 值判断是否选择了 "次卡" 类型
      this.isCardTypeSelected = newVal === 0;
      if (this.isCardTypeSelected) {
        // 如果选择了 "次卡" 类型，不对 cardDays 进行验证
        this.rules.cardDays = [
          { required: true, message: '卡的次数不能为空', trigger: 'blur' }
        ];
      } else {
        // 否则，要求 cardDays 为必填项，并提供相应的错误消息
        this.rules.cardDays = [
          { required: true, message: '卡的天数不能为空', trigger: 'blur' },
          { pattern: /^[0-9]+$/, message: '请输入数字', trigger: 'blur' }
        ];
      }
    },
  },
  created() {
    this.getList()
  },
  methods: {
    //会员卡默认值
    updateCardDays() {
      switch (this.form.memberType) {
        case 0: // 次卡
          this.form.cardDays = 10;
          break;
        case 1: // 月卡
          this.form.cardDays = 30;
          break;
        case 2: // 年卡
          this.form.cardDays = 365;
          break;
        case 3: // 体验卡
          this.form.cardDays = 7;
          break;
        default:
          this.form.cardDays = null;
      }
    },
    // 启用禁用状态按钮
    toggleDisableStatus(row) {
      const memberTypeName = row.memberTypeName
      this.$modal.confirm('是否确认修改卡名称为"' + memberTypeName + '"的状态？').then(() => {
        return updateManagementState(row)
      }).then(() => {
        this.getList()
        if (row.enableStatus === 1) {
          this.$message({
            message: '禁用成功',
            type: 'warning'
          })
        } else {
          this.$message({
            message: '启用成功',
            type: 'success'
          })
        }
      }).catch(() => {
      })
    },
    /** 查询会员类型列表 */
    getList() {
      this.loading = true
      listManagement(this.queryParams).then(response => {
        this.managementList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        venueUniqueIdentifier: null,
        memberType: null,
        cardDays: null,
        memberTypeName: null,
        memberTypeRemarks: null,
        enableStatus: null,
        createTime: null,
        updateTime: null,
        delFlag: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加会员类型'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getManagement(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改会员类型'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateManagement(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addManagement(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      // 检查 enableStatus 状态
      if (row.enableStatus === 0) {
        this.$modal.alert('该卡正在使用中，无法删除');
        return; // 阻止删除操作
      }
      // 如果 enableStatus 为 1，继续执行删除操作
      this.$modal.confirm('是否确认删除会员类型编号为"' + id + '"的数据项？').then(function() {
        return delManagement(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {
        // 可以在这里处理取消删除的情况
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('memberTypeManagement/management/export', {
        ...this.queryParams
      }, `management_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
